<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

</body>
<script>
    async function bulkRequests(requests,limit){
        const len = requests.length
        const result = new Array(len)
        const running = new Set()
        let index = 0
        const startTask = () => {
            const currentIndex = index++
            const task = requests[currentIndex]
            const promise = task().then(res => {
                result[currentIndex] = res
                running.delete(promise)
            }).catch(e => {
                result[currentIndex] = e
                running.delete(promise)
                throw e
            }).finally(()=>{
                if (index < len){
                    startTask()
                }
            })
            running.add(promise)
        }
        let num = len < limit ? len : limit
        for(let i = 0; i < num;i++){
            startTask()
        }
        return result
    }
    const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));

    const tasks = [
        () => delay(1000).then(() => 'Task 1'),
        () => delay(500).then(() => 'Task 2'),
        () => delay(2000).then(() => 'Task 3'),
        () => delay(750).then(() => 'Task 4'),
    ];
    bulkRequests(tasks, 2)
        .then(results => console.log(results));
</script>
</html>